<?php

defined('BASEPATH') or die('forbidden');

class Crontab_Controller Extends Controller {

    var $channel = array();
    var $type = array();
    var $frequence = array();
	var $maillist = array();	//邮件列表 
	
    function _init() {
        check_level(50, segment(0), segment(1), segment(2, 'index'));
        $this->channel = array(1 => translate('WORLD'), 2 => translate('CAMP'), 3 => translate('GANG'), 4 => translate('PRIVATECHAT'));
        $this->type = array(/*'notice' => translate('GENERAL_CRONTAB_NOTICE'), 'module' => translate('GENERAL_CRONTAB_MODULE'),*/'group_mail' => translate('GENERAL_CRONTAB_GROUP_MAIL'), 'url' => translate('GENERAL_CRONTAB_URL'), 'clearcache' => translate('CLEARACHE'));
        $this->frequence = array('once' => translate('ONCE'), 'repeat' => translate('REPEAT'));
        
        //type 0为单发，1为群发
        $sql = "SELECT autoid,mail_title FROM mail_message WHERE type = 1";
        $this->db->query($sql);
        while ($n = $this->db->get_array('default')) {
        	if(strlen($n['mail_title']) > 40)
        	{
        		$n['mail_title'] = substr($n['mail_title'],0,40)."...";
        	}
        	$this->maillist[$n['autoid']] = $n['mail_title'];
        }
    }

    function index() {
        set_area_list_view("flexigridarealist");
        $this->view->assign("typearr", $this->type);        
        $this->view->display("general/crontab/index");
    }

    function flexigrid() {
        list($colkey, $colsinfo, $where, $sortname, $sortorder, $offset, $rp, $page) = $this->common->get_flexigrid_params();
        $rows = array();

        $sql = "SELECT COUNT(*) AS num FROM {pre}crontab WHERE {$where}";
        $one = $this->db->one($sql);
        $total = $one['num'];
        $this->db->query("SELECT {$colsinfo} FROM {pre}crontab WHERE {$where}
                ORDER BY {$sortname} {$sortorder} 
                LIMIT {$offset},{$rp}");
        while ($n = $this->db->get_array('default')) {
            get_datetime(array(&$n['createtime'], &$n['starttime'], &$n['endtime']));
            $n['expiretime'] = $n['expiretime'] ? get_datetime($n['expiretime']) : translate('NOEXPIRE');
            $n['executetime'] = $n['executetime'] ? get_datetime($n['executetime']) : translate('UNDONE');
            $content = get_json_var($n['content']);
            $n['content'] = $content['msg'];
            $rows[] = array('id' => $n['id'], 'cell' => $n);
        }
        $result = array(
            'page' => $page,
            'total' => $total,
            'rows' => $rows
        );
        echo json_encode($result);
    }

    function add($id = 0) {
        if (is_submit()) {

            $rowdata = $_POST['row'];
            //先把邮件id保存起来
            $groupid = $rowdata['content']['group_mail_id'];
            //如果是群发邮件
         	
            print_r($_POST);
            echo " groupid = $groupid ";
            $areastr = '';
            foreach ($_POST['areaIds'] as $value)
            {
            	$areastr .=$value.",";
            }
            if (strlen($areastr)>0) {
            	$areastr = substr($areastr, 0,-1);
            }
            //echo " area:".addslashes(array_values($_POST['areaIds']));
            echo " areastr = $areastr ";
            print_r($rowdata);
        	if($rowdata['type'] == 'group_mail')
            {
            	echo " update mail_message areastr:$areastr groupid:$groupid ";
            	$ret = $this->db->update("mail_message", array('area_host'=>$areastr), array('autoid'=>$groupid));
            	if(false == $ret)
            	{
            		echo " update mail_message fail";
            		//cp_tips("error", $id);
            	}
            }
            
            $rowdata['content'] = addslashes(json_encode($rowdata['content']));
            $rowdata['createtime'] = time();
            $rowdata['state'] = 0;
            $rowdata['starttime'] = $rowdata['starttime'] ? strtotime($rowdata['starttime']) : 0;
            $rowdata['expiretime'] = $rowdata['expiretime'] ? strtotime($rowdata['expiretime']) : 0;
            $id = $rowdata['id'] = get_uuid();            
           
            $this->db->insert("{pre}crontab", $rowdata);
            insert_log(translate('MENU_GENERAL_CRONTAB'),translate('ADD'), $rowdata);
            set_async_data($_POST['areaIds'], translate('GENERAL_CRONTAB_ADD', $rowdata['title']), __CLASS__, __FUNCTION__, $rowdata);
            $count = $this->db->one("SELECT COUNT(*) AS num FROM {pre}crontab");
            $this->db->query("UPDATE {pre}crontab SET weigh='{$count['num']}' WHERE id='{$id}'");
            cp_tips("success", $id);
        }else 
        {
	        $this->view->assign("maillist",$this->maillist);
	        $this->view->assign("channel", $this->form->select("row[content][channel]", $this->channel, array(), array('id' => 'channel')));
	        $this->view->assign("type", $this->form->select("row[type]", $this->type, array(), array('id' => 'type')));
	        $this->view->assign("frequence", $this->form->select("row[frequence]", $this->frequence, array(), array('id' => 'frequence')));
	        set_area_list_view("arealist");        
	        $this->view->display("general/crontab/add");
        }
    }

    function edit($id = 0) {
        if ($id === 0)
        {
            error(translate('C_INVALID_PARAM_ID', $id));
        }
        $row = $this->db->one("SELECT * FROM {pre}crontab WHERE id='{$id}'");
        if (!is_array($row))
        {
            error(translate('C_INVALID_PARAM_ID', $id));
        }
        if (is_submit()) {
            $rowdata = $_POST['row'];
            //先把邮件id保存起来
            $groupid = $rowdata['content']['group_mail_id'];
            
            //print_r($_POST);
            //echo " groupid = $groupid ";
            $areastr = '';
            foreach ($_POST['areaIds'] as $value)
            {
            	$areastr .=$value.",";
            }
            if (strlen($areastr)>0) {
            	$areastr = substr($areastr, 0,-1);
            }
            //echo " area:".addslashes(array_values($_POST['areaIds']));
            //echo " areastr = $areastr ";
            
            $rowdata['content'] = addslashes(json_encode($rowdata['content']));
            $rowdata['starttime'] = $rowdata['starttime'] ? strtotime($rowdata['starttime']) : 0;
            $rowdata['expiretime'] = $rowdata['expiretime'] ? strtotime($rowdata['expiretime']) : 0;
            
            $result = $this->db->update("{pre}crontab", $rowdata, array('id' => $id));
            //echo " result = $result ";
            if ($result) {
                insert_log(translate('MENU_GENERAL_CRONTAB'),translate('EDIT'), $rowdata);
                $rowdata['id'] = $row['id'];
                set_async_data($_POST['areaIds'], translate('GENERAL_CRONTAB_EDIT', $rowdata['title']), __CLASS__, __FUNCTION__, $rowdata);
                
                print_r($rowdata);
                //如果是群发邮件
	         	if($rowdata['type'] == 'group_mail')
	            {
	            	echo " update mail_message areastr:$areastr groupid:$groupid ";
	            	$this->db->update("mail_message", array('area_host'=>$areastr), array('autoid'=>$groupid));
	            }
                
            }
            cp_tips("success", $id);
        }else 
        {
	        $row['content'] = get_json_array($row['content']);
	        $this->view->assign("channel", $this->form->select("row[content][channel]", $this->channel, $row['content']['channel'], array('id' => 'channel')));
	        $this->view->assign("type", $this->form->select("row[type]", $this->type, $row['type'], array('id' => 'type')));
	        $this->view->assign("frequence", $this->form->select("row[frequence]", $this->frequence, $row['frequence'], array('id' => 'frequence')));
	        set_area_list_view("arealist");
	        $this->view->assign("maillist",$this->maillist);
	        $this->view->display("general/crontab/edit", array('row' => $row));
        }
    }

    function del($id = 0) {
        $c = 0;
        $r = '';
        if ($id === 0)
            json_output($c, translate('C_INVALID_PARAM_ID', $id));
        $row = $this->db->one("SELECT * FROM {pre}crontab WHERE id='{$id}'");
        if (!is_array($row))
            json_output($c, translate('C_INVALID_PARAM_ID', $id));
        if ($this->db->delete('{pre}crontab', array('id' => $id))) {
            insert_log(translate('MENU_GENERAL_CRONTAB'),translate('DEL'), array('id:' => $id));
            $c = 1;
            $r = set_async_data($_POST['areaIds'], translate('GENERAL_CRONTAB_DEL', $row['title']), __CLASS__, __FUNCTION__, array('id' => $row['id']), true);
        } else {
            $r = translate('C_TIPS_ERROR_TEXT');
        }
        json_output($c, $r);
    }

    function multi() {
        $type = $this->input->post("type");
        $ids = $this->input->post("ids");
        $c = 0;
        $r = '';
        $allids = $ids = explode(',', $ids);
        if (count($ids) == 0) {
            $r = translate('C_INVALID_PARAMS');
        } else {
            $ids = "'" . implode("','", $ids) . "'";
            if ($type == 'delete') {
                $this->db->query("DELETE FROM {pre}crontab WHERE id IN ({$ids})");
                insert_log(translate('MENU_GENERAL_CRONTAB'),translate('MULTI_DEL'), array('ids' => implode(",", $allids)));
                $c = 1;
            } else if ($type == 'accept') {
                $this->db->query("UPDATE {pre}crontab SET state='1' WHERE id IN ({$ids})");
                $c = 1;
            } else if ($type == 'reject') {
                $this->db->query("UPDATE {pre}crontab SET state='0' WHERE id IN ({$ids})");
                $c = 1;
            } else {
                $r = translate('C_INVALID_PARAMS');
            }
        }
        if ($c == 1) {
            $r = set_async_data($_POST['areaIds'], translate('GENERAL_CRONTAB_MULTI_DEL', $type), __CLASS__, __FUNCTION__, array('ids' => $allids, 'type' => $type), true);
        }
        json_output($c, $r);
    }

}